const { get } = require('../model/http')
const { appId, appsecret,curUrl } = require('../config/config')
const db = require('../model/db');
const { genTimestap,randomStr } = require('../utils/util')
const crypto = require('crypto');

class Jsdk {

  async _getToken() {
    let url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appsecret}`
    let result = await get(url);
    return result.data.access_token;
  }

  async _getTicket(access_token) {
    let url = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi`;
    let result = await get(url);
    return result;
  }

  async _genTokenTickt() {
    let access_token = await this._getToken()
    console.log('token:', access_token)
    let result = await this._getTicket(access_token)
    let { ticket, expires_in } = result.data;
    return {
      access_token,
      ticket,
      expires_in
    }
  }

  async api(ctx) {
    let options = {};
    //1:查询数据库，是否存在token
    let timestamp = genTimestap();
    let rs = await db('select * from token');
    if (rs.length > 0) {
      //判断数据是否过期
      console.log('get token from db', rs)
      let start_time = rs[0].start_time;
      let expires_in = rs[0].expires_in;
      //判断token是否过期
      if (timestamp - start_time > expires_in) {
        //token的更新
        options =await this._genTokenTickt()
        let {
          access_token,
          ticket,
          expires_in
        } = options;
        db('update token set access_token=?,ticket=? , expires_in=?', [access_token, ticket, expires_in]);
      } else {
        options = rs[0];
      }
    } else {
      //1;获取access_token
      //https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
      // let access_token = await this._getToken()
      //2:第一步拿到的access_token 采用http GET方式请求获得jsapi_ticket（有效期7200秒，开发者必须在自己的服务全局缓存jsapi_ticket）：https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
      // console.log('token:', access_token)
      // let result = await this._getTicket(access_token)
      // let { ticket, expires_in } = result.data;
      // console.log('ticket:', result.data)
      options = await this._genTokenTickt()
      await db('insert into token set ?', { ...options, start_time: timestamp })
    }
    console.log('options:',options)

    let nonceStr = randomStr(32);

    let string1=`jsapi_ticket=${options.ticket}&noncestr=${nonceStr}&timestamp=${timestamp}&url=${curUrl}`
    let signature = crypto.createHash('sha1').update(string1).digest('hex');

    ctx.body = {
      appId, // 必填，公众号的唯一标识
      timestamp, // 必填，生成签名的时间戳
      nonceStr, // 必填，生成签名的随机串
      signature// 必填，签名
    }
  }
}


module.exports = new Jsdk()